package cmc

import (
	"context"
	"fmt"
	model "service/model/crm_base"
	"service/model/mod"
	"time"

	comm "gitee.com/cloudapex/protos/comm/pb"
	"gitee.com/cloudapex/ulern/util"

	gpb "gitee.com/cloudapex/protos/crm_base/pb"
	"gitee.com/cloudapex/ulern/htp"
	"github.com/gin-gonic/gin"
)

/**
 *说明： 机会创建
 *	   1.BaseBase 手机号基础信息
 *     2.BaseProject 项目机会信息
 *
 */

type AddPool struct {
	Id          uint64 `json:"id" form:"id" binding:"omitempty"`                   //机会ID(11位)
	Name        string `json:"name" form:"name" binding:"omitempty"`               //学员姓名
	Address     string `json:"address" form:"address" binding:"omitempty"`         //地域
	Sex         int64  `json:"sex" form:"sex" binding:"omitempty"`                 //性别 0 默认 1 男 2 女  性别
	Srank       int64  `json:"srank" form:"srank" binding:"omitempty"`             //学历 1 初中以下, 2 中专 3 高中 4 大专 5 本科， 6 硕士， 7 博士
	Major       string `json:"major" form:"major" binding:"omitempty"`             //专业
	Phone       int64  `json:"phone" form:"phone" binding:"omitempty"`             //手机号（ 可以有默认值，为支持网销团队 ）
	DeputyNo    int64  `json:"deputyNo" form:"deputyNo" binding:"omitempty"`       //副号
	WeChar      string `json:"weChar" form:"weChar" binding:"omitempty"`           //微信号
	State       int64  `json:"state" form:"state" binding:"omitempty"`             //本库状态： 1 - 100 ： 可以拨打状态 100 - 200 不可拨打状态( 100 空号， 101 静默号 )
	Qq          int64  `json:"qq" form:"qq" binding:"omitempty"`                   //QQ号
	AId         uint64 `json:"aid" form:"aid" binding:"omitempty"`                 //机会的项目ID proid+bid(14位)
	CId         int64  `json:"cId" form:"cId" binding:"omitempty"`                 //公司id
	BId         uint64 `json:"bId" form:"bId" binding:"omitempty"`                 //base_base id
	PId         int64  `json:"pId" form:"pId" binding:"omitempty"`                 //project id
	UId         int64  `json:"uId" form:"uId" binding:"omitempty"`                 //当前领取坐席ID
	Station     int64  `json:"station" form:"station" binding:"omitempty"`         //站点ID
	StationShow uint64 `json:"stationShow" form:"stationShow" binding:"omitempty"` //站点可见范围（ 可分配数据区间 ）
	ShowId      uint64 `json:"showId" form:"showId" binding:"omitempty"`           //可见范围ID
	FirstId     int64  `json:"firstId" form:"firstId" binding:"omitempty"`         //首次领取坐席
	ToAt        int64  `json:"toAt" form:"toAt" binding:"omitempty"`               //最近一次领取时间
	SId         string `json:"sId" form:"sId" binding:"omitempty"`                 //来源id 渠道  导入数据需追加来源ID
	Info        string `json:"info" form:"info" binding:"omitempty"`               //机会详情
	CallCount   int64  `json:"callCount" form:"callCount" binding:"omitempty"`     //累计拨打次数
	CallLength  int64  `json:"callLength" form:"callLength" binding:"omitempty"`   //累计拨打时长
	Logic       int64  `json:"logic" form:"logic" binding:"omitempty"`             //逻辑库-1 首资，2 公海，3 静默库，4 效率库，5 成交库，6 垃圾库
	BackAt      int64  `json:"backAt" form:"backAt" binding:"omitempty"`           //回公海时间 ( 由效率库回公海的时间 )
	Levels      int64  `json:"levels" form:"levels" binding:"omitempty"`           //意向度 S A B C D
	InType      int64  `json:"inType" form:"inType" binding:"omitempty"`           //入库方式 1首资入库，2销售创建，3批量导入
	SAccount    string `json:"sAccount" form:"sAccount" binding:"omitempty"`       //推广账户
	SWay        int64  `json:"sWay" form:"sWay" binding:"omitempty"`               //推广方式（sem,信息流）
}

func (this *AddPool) Handle(c *gin.Context, ctx context.Context) htp.Response {
	jwtUser := mod.CurrUser(c)
	list, err := model.Base.AddPool(ctx, &gpb.BasePoolReq{
		BasePool: &gpb.BasePool{
			BaseProject: &gpb.BaseProject{
				InType:      2,
				UId:         jwtUser.UId,
				ShowId:      jwtUser.ShowId[0],
				StationShow: mod.SectionMaxLv(jwtUser.ShowId),
				Station:     1,
				FirstId:     jwtUser.UId,
				PId:         this.PId,
				CId:         jwtUser.CId,
				Logic:       2,
			},
			BaseProTg: &gpb.BaseProTg{},
			BaseBase: &gpb.BaseBase{
				Phone:    this.Phone,
				Name:     this.Name,
				Sex:      this.Sex,
				Major:    this.Major,
				WeChar:   this.WeChar,
				Address:  this.Address,
				DeputyNo: this.DeputyNo,
			},
		},
		Type: 2,
	})
	fmt.Println(err, "err ")
	if err != nil {
		return htp.RespModelErr("", err)
	}
	fmt.Println("list :   ", list)
	// 添加工作池
	if _, err = model.Work.WorkPoolAdd(ctx, &gpb.WorkPool{
		Id:        list.BpId,
		CId:       jwtUser.CId,
		BId:       list.BId,
		PId:       this.PId,
		UId:       jwtUser.UId,
		UName:     jwtUser.Name,
		Phone:     this.Phone,
		ShowId:    mod.SectionMaxLv(jwtUser.ShowId),
		TestAddre: this.Address,
		Logic:     2,
		At:        time.Now().Unix(),
	}); err != nil {
		return htp.RespModelErr("添加工作池", err)
	}
	return htp.RespOK("", nil)
}

/**
 *说明：查询单条记录
 */
type SelectOutNode struct {
	CsId uint64 `json:"cs_id" form:"cs_id" binding:"omitempty"` //客户id
}

type SelectOutNodeRes struct {
	Id     int64  `json:"id" form:"id"`         //唯一ID
	BpId   uint64 `json:"bpId" form:"bpId"`     //base_project 机会ID
	OuType int64  `json:"ouType" form:"ouType"` //登记原因 1.客户辱骂 2.客户不需要 3.在别的学校报名了 4.其他
	Node   string `json:"node" form:"node"`     //备注
	OperId int64  `json:"operId" form:"operId"` //审核人
	At     int64  `json:"at" form:"at"`         //登记时间
}

func (this *SelectOutNode) Handle(c *gin.Context, ctx context.Context) htp.Response {
	rsp, err := model.PoolOutNode.SelectPoolOutNode(ctx, &gpb.PoolOutNode{
		BpId: this.CsId,
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	item := SelectOutNode{}
	if errs := util.Convert(&item, rsp.PoolOut); nil != errs {
		return htp.RespModelErr("", errs)
	}
	return htp.RespOK("", item)
}

/**
 *说明：机会回库
 */
type DelWorkPool struct {
	CsId  uint64 `json:"cs_id" form:"cs_id" binding:"omitempty"` //客户id
	Logic int64  `json:"logic" form:"logic" binding:"omitempty"` //逻辑库-1 首资，2 公海，3 静默库，4 效率库，5 成交库，6 垃圾库
}

func (this *DelWorkPool) Handle(c *gin.Context, ctx context.Context) htp.Response {
	//先查该客户id是否有备注信息，如果有工作池删除回公海 没有回首资  back必调用
	if this.CsId == 0 {
		return htp.RespModelErr("客户id不可为空", nil)
	}
	if this.Logic == 1 {
		fage, err := model.PoolNodeSer.SelectPoolNode(ctx, &gpb.PoolNode{BpId: this.CsId})
		if nil != err {
			return htp.RespModelErr("", err)
		}
		if fage.PoolNode != nil {
			if _, err := model.Base.SetPoolLogic(ctx, &gpb.PoolLogicReq{Id: this.CsId, Logic: 2}); nil != err {
				return htp.RespModelErr("", err)
			}
		} else {
			if _, err := model.Base.SetPoolLogic(ctx, &gpb.PoolLogicReq{Id: this.CsId, Logic: 1}); nil != err {
				return htp.RespModelErr("", err)
			}
		}
	} else {
		if _, err := model.Base.SetPoolLogic(ctx, &gpb.PoolLogicReq{Id: this.CsId, Logic: 2}); nil != err {
			return htp.RespModelErr("", err)
		}
	}
	if _, err := model.Work.DelWorkPool(ctx, &comm.BaseReq{Id: this.CsId}); nil != err {
		return htp.RespModelErr(fmt.Sprintf("%d 从工作池删除失败 :%s", this.CsId, err.Error()), err)
	}
	if _, err := model.Base.BackPool(ctx, &gpb.BaseProject{Id: this.CsId}); nil != err {
		return htp.RespModelErr(fmt.Sprintf("%d 修改参数basepool参数 :%s", this.CsId, err.Error()), err)
	}
	return htp.RespOK("回库成功", nil)
}

/**
 * @explain : 添加备注
 * @Request method :  GET
 * @address :
 * @remarks :
 **/
type PoolNodeAdd struct {
	Id       uint64 `json:"id" form:"id" binding:"omitempty"`             //唯一ID
	BId      uint64 `json:"bId" form:"bId" binding:"omitempty"`           //base_base Id
	BpId     uint64 `json:"bpId" form:"bpId" binding:"omitempty"`         //base_project 机会ID
	UId      int64  `json:"uId" form:"uId" binding:"omitempty"`           //登记坐席
	PId      int64  `json:"pId" form:"pId" binding:"omitempty"`           //项目ID
	NodeType int64  `json:"nodeType" form:"nodeType" binding:"omitempty"` //沟通类型 1.正常接通 2.未接通 3.关/停机 4.空号
	AnsAt    int64  `json:"ansAt" form:"ansAt" binding:"omitempty"`       //预约回访时间
	Node     string `json:"node" form:"node" binding:"omitempty"`         //备注
	At       int64  `json:"at" form:"at" binding:"omitempty"`             //登记时间
	NType    int64  `json:"nType" form:"nType" binding:"omitempty"`       //类型: 1 备注, 2 其他标签
}

func (this *PoolNodeAdd) Handle(c *gin.Context, ctx context.Context) htp.Response {
	jwtUser := mod.CurrUser(c)
	if _, err := model.PoolNodeSer.PoolNodeAdd(ctx, &gpb.PoolNode{
		BId:      this.BId,
		BpId:     this.BpId,
		UId:      jwtUser.UId,
		PId:      this.PId,
		NodeType: this.NodeType,
		AnsAt:    this.AnsAt,
		Node:     this.Node,
		At:       time.Now().Unix(),
		NType:    this.NType,
	}); nil != err {
		return htp.RespModelErr("", err)
	}
	if _, err := model.Work.EditWorkPool(ctx, &gpb.WorkPool{
		UId:    jwtUser.UId,
		Id:     this.BpId,
		NoteAt: time.Now().Unix(),
		Submit: this.AnsAt,
	}); nil != err {
		return htp.RespModelErr("", err)
	}
	return htp.RespOK("备注添加成功", nil)
}

/**
 * @explain : 库存来10条
 * @Request method : GET
 * @address :
 * @remarks :
 **/

type Inventory struct {
	PId int64 `json:"pId" form:"pId" binding:"omitempty"` //project id
}

func (this *Inventory) Handle(c *gin.Context, ctx context.Context) htp.Response {
	user := mod.CurrUser(c)
	//fmt.Println(user.UId)
	//return htp.RespOK(fmt.Sprintf("成功获取%d条库存数据", 0), nil)
	// 从公海中取30条,随机选10条
	rsp, err := model.Base.GetPoolList(ctx, &gpb.BasePoolReq{
		Page:    1,
		Count:   10,
		DesClum: 1, // 按入库时间
		IsDes:   1, // 倒序
		Type:    1, // 未分配
		BasePool: &gpb.BasePool{
			BaseBase: &gpb.BaseBase{},
			BaseProject: &gpb.BaseProject{
				CId:   user.CId,
				PId:   this.PId,
				Logic: int64(model.EBaseL_Open),
			},
			BaseProTg: &gpb.BaseProTg{},
		},
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	//if len(rsp.BasePool) < 10 {
	//	return htp.RespErr(1, "机会不足十条", err)
	//}

	count := 0
	//indexs := util.RandIntDis(len(rsp.BasePool), 10)
	for _, index := range rsp.BasePool {
		item := index
		if _, err := model.Base.EditPool(ctx, &gpb.BasePoolReq{BasePool: &gpb.BasePool{
			BaseProject: &gpb.BaseProject{Id: uint64(item.BaseProject.Id), UId: user.UId, ShowId: user.ShowId[0]},
			BaseBase:    &gpb.BaseBase{},
			BaseProTg:   &gpb.BaseProTg{},
		}}); err != nil {
			util.Warn("获取机会失败:%s", err.Error())
			continue
		}
		// 添加工作池
		if _, err = model.Work.WorkPoolAdd(ctx, &gpb.WorkPool{
			Id:     item.BaseProject.Id,
			CId:    user.CId,
			BId:    item.BaseBase.Id,
			PId:    item.BaseProject.PId,
			UId:    user.UId,
			UName:  user.Name,
			Phone:  item.BaseBase.Phone,
			ShowId: mod.SectionMaxLv(user.ShowId),
			Levels: item.BaseProject.Levels,
			Info:   item.BaseProject.Info,
			Logic:  item.BaseProject.Logic,
			At:     time.Now().Unix(),
		}); err != nil {
			util.Warn("添加工作池失败:%s", err.Error())
			continue
		}
		count++
	}

	return htp.RespOK(fmt.Sprintf("成功获取%d条库存数据", count), nil)
}
